在 c# 中将数据从 UI 线程传递到另一个线程

本文关键字:线程 另一个 UI 数据 | 更新日期: 2023-09-27 18:33:21

如何将

数据从主线程传递到在不同线程中连续运行的方法?我有一个计时器,其中的值将不断递增,并且在每个计时器时钟周期事件中,该数据将传递给不同线程中的方法。请帮忙。我对线程知之甚少。

在 c# 中将数据从 UI 线程传递到另一个线程

您可以使用队列将数据发送到另一个线程,您锁定该线程以进行访问。这可确保发送到另一个线程的所有数据最终得到处理。您实际上不需要将其视为将数据"发送"到另一个线程,而是管理共享数据的锁定,以便它们不会同时访问它(这可能会导致灾难!

Queue<Data> _dataQueue = new Queue<Data>();
void OnTimer()
{
    //queue data for the other thread
    lock (_dataQueue)
    {
        _dataQueue.Enqueue(new Data());
    }
}
void ThreadMethod()
{
    while (_threadActive)
    {
        Data data=null;
        //if there is data from the other thread
        //remove it from the queue for processing
        lock (_dataQueue)
        {
            if (_dataQueue.Count > 0)
                data = _dataQueue.Dequeue();
        }
        //doing the processing after the lock is important if the processing takes
        //some time, otherwise the main thread will be blocked when trying to add
        //new data
        if (data != null)
            ProcessData(data);
        //don't delay if there is more data to process
        lock (_dataQueue)
        {
            if (_dataQueue.Count > 0)
                continue;
        }
        Thread.Sleep(100);
    }
}

如果您使用的是 Windows 窗体,则可以执行以下操作:

在表单中添加属性

private readonly System.Threading.SynchronizationContext context;
public System.Threading.SynchronizationContext Context
{
    get{ return this.context;}
}

在窗体构造函数中设置属性

this.context= WindowsFormsSynchronizationContext.Current;

使用此属性将其作为构造函数参数传递给后台辅助角色。这样,您的工作人员将了解您的 GUI 上下文。在后台辅助角色中创建类似的属性。

private readonly System.Threading.SynchronizationContext context;
public System.Threading.SynchronizationContext Context
{
    get{ return this.context;}
}
public MyWorker(SynchronizationContext context)
{
    this.context = context;
}

更改您的 Done() 方法:

void Done()
{
    this.Context.Post(new SendOrPostCallback(DoneSynchronized), null);
}
void DoneSynchronized(object state)
{
    //place here code You now have in Done method.
}

在完成同步中,您应该始终处于 GUI 线程中。

上面的答案正是来自这个线程。重复标记。

可能的重复项