找不到后台工作人员

Posted

技术标签:

【中文标题】找不到后台工作人员【英文标题】:BackgroundWorker not found 【发布时间】:2015-11-18 09:13:18 【问题描述】:

我在 windows phone 8.1 中使用 System.componentmodel 引用来获取 BackgroundWorker,但每次我放置 BackgroundWorker 时它都会给我

错误 CS0246 找不到类型或命名空间名称“BackgroundWorker”(您是否缺少 using 指令或程序集引用?) HealthBand C:\Users\husam\Desktop\Projects\HealthBand\HealthBand\ConnectionManager .cs 16

我尝试添加引用,但它说它已经添加 当我把

using System.ComponentModel;

它说使用指令是不必要的

这是我的代码

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using System.ComponentModel;

namespace HealthBand

/// <summary>
/// Class to control the bluetooth connection to the Arduino.
/// </summary>
public class ConnectionManager

    private BackgroundWorker dataReadWorker;
    /// <summary>
    /// Socket used to communicate with Arduino.
    /// </summary>
    private StreamSocket socket;

    /// <summary>
    /// DataWriter used to send commands easily.
    /// </summary>
    private DataWriter dataWriter;

    /// <summary>
    /// DataReader used to receive messages easily.
    /// </summary>
    private DataReader dataReader;

    /// <summary>
    /// Thread used to keep reading data from socket.
    /// </summary>


    /// <summary>
    /// Delegate used by event handler.
    /// </summary>
    /// <param name="message">The message received.</param>
    public delegate void MessageReceivedHandler(string message);

    /// <summary>
    /// Event fired when a new message is received from Arduino.
    /// </summary>
    public event MessageReceivedHandler MessageReceived;

    /// <summary>
    /// Initialize the manager, should be called in OnNavigatedTo of main page.
    /// </summary>
    public void Initialize()
    
        socket = new StreamSocket();
        dataReadWorker = new BackgroundWorker();
        dataReadWorker.WorkerSupportsCancellation = true;
        dataReadWorker.DoWork += new DoWorkEventHandler(ReceiveMessages);
    

    /// <summary>
    /// Finalize the connection manager, should be called in OnNavigatedFrom of main page.
    /// </summary>
    public void Terminate()
    
        if (socket != null)
        
            socket.Dispose();
        
        if (dataReadWorker != null)
        
            dataReadWorker.CancelAsync();
        
    

    /// <summary>
    /// Connect to the given host device.
    /// </summary>
    /// <param name="deviceHostName">The host device name.</param>
    public async void Connect(HostName deviceHostName)
    
        if (socket != null)
        
            await socket.ConnectAsync(deviceHostName, "1");
            dataReader = new DataReader(socket.InputStream);
            dataReadWorker.RunWorkerAsync();
            dataWriter = new DataWriter(socket.OutputStream);
        
    

    /// <summary>
    /// Receive messages from the Arduino through bluetooth.
    /// </summary>
    private async void ReceiveMessages(object sender, DoWorkEventArgs e)
    
        try
        
            while (true)
            
                // Read first byte (length of the subsequent message, 255 or less). 
                uint sizeFieldCount = await dataReader.LoadAsync(1);
                if (sizeFieldCount != 1)
                
                    // The underlying socket was closed before we were able to read the whole data. 
                    return;
                

                // Read the message. 
                uint messageLength = dataReader.ReadByte();
                uint actualMessageLength = await dataReader.LoadAsync(messageLength);
                if (messageLength != actualMessageLength)
                
                    // The underlying socket was closed before we were able to read the whole data. 
                    return;
                
                // Read the message and process it.
                string message = dataReader.ReadString(actualMessageLength);
                MessageReceived(message);
            
        
        catch (Exception ex)
        
            Debug.WriteLine(ex.Message);
        

    

    /// <summary>
    /// Send command to the Arduino through bluetooth.
    /// </summary>
    /// <param name="command">The sent command.</param>
    /// <returns>The number of bytes sent</returns>
    public async Task<uint> SendCommand(string command)
    
        uint sentCommandSize = 0;
        if (dataWriter != null)
        
            uint commandSize = dataWriter.MeasureString(command);
            dataWriter.WriteByte((byte)commandSize);
            sentCommandSize = dataWriter.WriteString(command);
            await dataWriter.StoreAsync();
        
        return sentCommandSize;
    


请问我该如何解决这个错误

【问题讨论】:

根据at MSDN 所写的内容,BackgroundWorker 仅适用于 WP7.0 和 WP7.1 的 Windows Phone。 没有办法解决它或修改代码使其工作 【参考方案1】:

BackgroundWorker 在 WP8.1 中不受支持。不要使用它,而是使用 Task.Run 方法将您的工作重定向到 ThreadPool。正如文章Asynchronous Programming with Async and Await 所说:

在几乎所有情况下,基于异步的异步编程方法都优于现有方法。特别是,对于 IO 绑定操作,这种方法比 BackgroundWorker 更好,因为代码更简单,您不必防范竞争条件。与 Task.Run 结合使用时,对于 CPU 密集型操作,异步编程比 BackgroundWorker 更好,因为异步编程将运行代码的协调细节与 Task.Run 转移到线程池的工作分开。

如需更多修复、代码示例和比较,请访问Stephen Cleary's blog。

【讨论】:

代码不工作任何人都可以帮助将其转换为 Task.Run 代码 @HossamFuad 尝试将您的ReceiveMessages 转换为Task,而不是启动工作人员dataReadWorker.RunWorkerAsync(); 放入await Task.Run(ReceiveMessages)。您是如何尝试转换的? @HossamFuad 由于您也使用取消,那么this pattern 也应该有所帮助。 我正在尝试解决这个问题,但我对这种类型的代码不熟悉,所以请进一步帮助我 @HossamFuad 我不相信我可以更好地解释斯蒂芬在他的博客上的解释。如果不了解您的尝试并了解您的应用程序的行为方式,也很难提供进一步的帮助。

以上是关于找不到后台工作人员的主要内容,如果未能解决你的问题,请参考以下文章

后台工作人员仍然冻结 ui

程序员找不到工作,先去外包过渡2年?千万别去

在后台运行 IOS 应用程序新开发人员

为啥很多学完了Java,依旧找不到工作?

NSNull floatValue intValue 找不到指定方法解决方式

找不到工作区文件('angular.json')